import Ball from "./Ball";

/**
*
* @ author:JiangChencheng
* @ email:744578095@qq.com
* @ data: 2021-10-29 16:23
*/
export default class Prop extends Laya.Script {

    constructor() {
        super();
        this.rowId = 0
        this.txt_count = null
        this.count = 0
        this.sign = null
    }

    Init(count,rowId,sign) {
        this.rowId = rowId
        this.count = count
        this.txt_count.text = count
        this.sign = sign
        // 闪电球碰撞事件码
        Laya.stage.on("DamageRow",this,this.onDamageRow)
    }

    onAwake() {
        this.txt_count = this.owner.getChildByName("txt_count")
        
    }
    onDestroy(){
        Laya.stage.off("DamageRow",this,this.onDamageRow)
    }

    onDamageRow(rowId,damage) {

        if (rowId == this.rowId){
            this.onDamage(damage)
        }

    }


    onDamage(damage){
        this.count-=damage
        this.txt_count.text = this.count
        if (this.count <= 0) {
            // this.owner.destroy()
            this.onRecover()
        }
        
    }   

    onRecover(){
        Laya.stage.off("DamageRow",this,this.onDamageRow)
        //回收进对象池
        this.owner.visible=false;
        this.owner.active=false;
        Laya.Pool.recover(this.sign,this.owner)

    }




    onTriggerEnter(other){

        if(other.owner.name == "ball") {
            var damage = other.owner.getComponent(Ball).damage
            var damageRow = other.owner.getComponent(Ball).damageRow
            if (damageRow == true) {
                // todo 特效
                Laya.stage.event("DamageRow",[this.rowId,damage])
            }else {
                this.onDamage(damage)
            }
            if (this.count > 0) {
                this.playAnimation()
            }
            Laya.stage.event("AddScore",damage)
            
        }

    }

    playAnimation(){
        var sp = this.owner.getChildByName("sp")
        Laya.Tween.clearAll(sp)
        // 还原位置 
        sp.pos(0,0)

        var x = sp.x
        var y = sp.y
        var offset = 4
        Laya.Tween.to(sp,{x:x-offset},10,null,new Laya.Handler(this,function(){
            Laya.Tween.to(sp,{x:x+offset},20,null,new Laya.Handler(this,function(){
                Laya.Tween.to(sp,{x:x},10,null,new Laya.Handler(this,function(){
                    Laya.Tween.to(sp,{y:y-offset},10,null,new Laya.Handler(this,function(){
                        Laya.Tween.to(sp,{y:y+offset},20,null,new Laya.Handler(this,function(){
                            Laya.Tween.to(sp,{y:y},10)
                        }))
                    }))
                }))
            }))
        }))
    }

}